﻿using importBarcodes;
using LitJson2;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using WindowsFormsApplication1.common;
using WindowsFormsApplication1.Model;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        JsonData jd;
        string priceListApiUrl = "/api/v3/priceSchemes/?fromSite=694904204619154432&fc=636958571841455104&rnd_rnd_rnd=1527822317329&%7Bpage%7D=1&%7BpageSize%7D=20&%7Bexpand%7D=%5BgymKind%2CticketTimeoutSetting%2CaddSettings.*%2CproductGroups.*%2CproductGroups.products.*%2CproductGroups.products.product%2CtimePrices.*%5D&name*like=&gymKind.name*like=&priceType*in=%5B1%2C4%5D";
        public StringBuilder sbData;
        public static Dictionary<string, object> defaultDict;

        private void btnGetPriceList_Click(object sender, EventArgs e)
        {
#if localTest
            List<Price> plist = new List<Price>();
            plist.Add(new Price() { name = "我是家庭票1", id = "1", price = "1.4"});
            plist.Add(new Price() { name = "我是家庭票2", id = "2", price = "1.5" });
            plist.Add(new Price() { name = "我是家庭票3", id = "3", price = "1.6" });
            cbPrice.DataSource = plist;
#endif
            try
            {
                string url = txtHost.Text + priceListApiUrl;
#if !localTest
                string responseString = HttpHelper.GetResponseString(HttpHelper.CreateGetHttpResponse(url, 50, null, null));
                jd = JsonMapper.ToObject(responseString);
                if (jd["data"] == null)
                {
                    MessageBox.Show(responseString);
                    return;
                }
                List<Price> list = new List<Price>();
                foreach (JsonData item in jd["data"]["content"])
                {
                    list.Add(new Price() { name = GetStringValue(item["name"]), id = GetStringValue(item["id"]), price = GetStringValue(item["price"]) });
                }
                cbPrice.DataSource = list;
#endif
                cbPrice.ValueMember = "id";
                cbPrice.DisplayMember = "name";
                //MessageBox.Show(responseString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\r" + ex.StackTrace);
            }
        }
        private string GetStringValue(object obj)
        {
            if (obj == null)
            {
                return "";
            }
            else
            {
                return obj.ToString();
            }
        }

        private void cbPrice_SelectedIndexChanged(object sender, EventArgs e)
        {
            Price p = (Price)cbPrice.SelectedItem;
            txtItemName.Text = p.name;
            txtPrice.Text = p.price;
        }

        private void btnCreateSql_Click(object sender, EventArgs e)
        {
            var sbData = new StringBuilder();
            //            INSERT  INTO `third_order_item`
            //(`id`,`create_time`,`creator_client_id`,`creator_name`,`enable`,`update_time`,`updater_client_id`,`updater_name`,`version`,`item_name`,`number`,`price`,`qr_code`,
            //`order_id`,`in_number`,`out_number`,`in_time`,`out_time`,`code`,`effective_date`,`invalid_date`,`item_id`) 
            //VALUES (3938272027,'2018-05-30 16:06:12',0,NULL,1,'2018-05-30 18:13:09',0,NULL,2,'测试票1',1,'10.00','123456789',NULL,1,0,'2018-05-30 18:13:09',NULL,NULL,NULL,NULL,NULL);
        }
        private Dictionary<string, object> GetDefalutDict()
        {
            var id = Convert.ToInt64(txtId.Text);
            var time = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            var ticketsMap = new Dictionary<String, Object>();
            ticketsMap["id"] = id;
            ticketsMap["create_time"] = time;
            ticketsMap["creator_client_id"] = 0;
            ticketsMap["creator_name"] = "导入";
            ticketsMap["enable"] = 1;

            ticketsMap["update_time"] = time;
            ticketsMap["version"] = "15";

            ticketsMap["item_name"] = txtItemName.Text;
            ticketsMap["number"] = 1;
            ticketsMap["price"] = txtPrice.Text;
            //ticketsMap["qr_code"] = arr[1];
            //ticketsMap["code"] = arr[0];
            ticketsMap["order_id"] = null;
            ticketsMap["in_number"] = 0;
            ticketsMap["out_number"] = 0;

            ticketsMap["in_time"] = null;
            ticketsMap["out_time"] = null;
           

            ticketsMap["effective_date"] = dtpEffectiveDate.Text;
            ticketsMap["invalid_date"] = dtpInvalidDate.Text;



            ticketsMap["item_id"] = ((Price)cbPrice.SelectedItem).id;
            return ticketsMap;
        }

        string[] path = null;
        public long linecount = 0;

        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                var textFileName = "条形码";
                defaultDict = GetDefalutDict();

                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Title = "打开";
                ofd.Filter = "所有文件|*.csv";
                ofd.Multiselect = true;
                ofd.InitialDirectory = Application.StartupPath;
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    path = ofd.FileNames;
                }
                if (path == null)
                {
                    return;
                }
                Thread worker = new Thread(delegate()
                {
                    DateTime dt_read_txt = DateTime.Now;
                    StringBuilder sbData = new StringBuilder();
                    linecount = 0;
                    long id = Convert.ToInt64(defaultDict["id"]);
                   
                    for (int i = 0; i < path.Length; i++)
                    {
                        using (StreamReader sr = new StreamReader(path[i], System.Text.Encoding.GetEncoding("gb2312")))
                        {
                            string line = string.Empty;
                            while ((line = sr.ReadLine()) != null)
                            {
                                //如果读出一行不是空字符串
                                if (line.Trim() != "")
                                {
                                    linecount++;
                                    UpdateLineCount((cbIgnoreFirstLine.Checked ? (linecount - 1) : linecount).ToString());
                                    if (linecount < 1 && cbIgnoreFirstLine.Checked || sr.EndOfStream)
                                    {
                                        //第一行遗弃
                                        continue;
                                    }
                                    //当遇到内容带有,的时候，就需要正则去匹配了
                                    Regex CSVParser = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                                    var arr = CSVParser.Split(line);

                                    //importQrcode(sbData, id, arr);
                                    importBarcode(sbData, arr);
                                    if (linecount % 10000 == 0)
                                    {
                                        saveTextFile(sbData.ToString(), textFileName, "sql", true);
                                        sbData.Length = 0;
                                    }
                                }
                               
                            }
                        }
                    }
                    saveTextFile(sbData.ToString(), textFileName, "sql", true);
                    sbData.Length = 0;
                    MessageBox.Show("生成脚本完毕");
                    System.Diagnostics.Process.Start("ExpLorer", Application.StartupPath+"\\");
                });
                worker.IsBackground = true;
                worker.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n\r" + ex.StackTrace);
            }
        }

        private void importBarcode(StringBuilder sbData, string[] arr)
        {
            if (arr.Length >= 6)
            {
                string product_barcode = @"INSERT  INTO `product_barcode`(`create_time`,`creator_client_id`,`creator_name`,`enable`,`update_time`,`updater_client_id`,`updater_name`,`version`,`code`,`json`) 
VALUES ('2018-06-04 17:41:38',0,NULL,1,'2018-06-04 17:41:38',0,NULL,0,'{0}','{1}');";
                Barcode barcode = new Barcode { barcode = arr[0].Trim(), name = arr[1].Trim(), type = arr[3].Trim(), unit = arr[4].Trim(), origincountry = arr[5].Trim() };
                var json = JsonMapper.ToJson(barcode);
                sbData.Append(string.Format(product_barcode, barcode.barcode.Trim(), json) + "\n");
            }
        }

        private void importQrcode(StringBuilder sbData, long id, string[] arr)
        {
            var ticketsMap = defaultDict;

            ticketsMap["id"] = id + linecount;
            ticketsMap["qr_code"] = arr[1];
            ticketsMap["code"] = arr[0];

            string ticketsSqlHeader = @"insert into `third_order_item` (";
            string ticketsSqlValues = "values(";

            foreach (var entry in ticketsMap)
            {
                ticketsSqlHeader += entry.Key + ",";
                if (entry.Value != null)
                {
                    ticketsSqlValues += "'" + entry.Value + "',";
                }
                else
                {
                    ticketsSqlValues += "NULL,";
                }
            }

            ticketsSqlValues = ticketsSqlValues.Substring(0, ticketsSqlValues.Length - 1);
            ticketsSqlHeader = ticketsSqlHeader.Substring(0, ticketsSqlHeader.Length - 1);

            ticketsSqlHeader += ")";
            ticketsSqlValues += ");";

            string ticketsResult = ticketsSqlHeader + ticketsSqlValues;
            sbData.Append(ticketsResult + "\n");
        }

        #region //保存text
        public static void saveTextFile(string log, string txtName, string expandedName, bool isAppend = false)
        {
            //log = DateTime.Now.ToString() + " : " + log;
            string path = Application.StartupPath + "\\";
            if (isAppend == true && File.Exists(path + @"\" + txtName + "." + expandedName))
            {
                StreamWriter SW;
                SW = File.AppendText(path + @"\" + txtName + "." + expandedName);
                SW.WriteLine(log);
                SW.Close();
            }
            else
            {
                StreamWriter SW;
                SW = File.CreateText(path + @"\" + txtName + "." + expandedName);
                SW.WriteLine(log);
                SW.Close();
            }

        }
        #endregion

        public void UpdateLineCount(string text)
        {
            //无参数,但是返回值为bool类型
            this.Invoke(new Func<bool>(delegate()
            {
               labelCurrent.Text ="csv记录统计:"+ text;
                return true; //返回值
            }));
        }
    }
}
